//
//  IndexPageViewControll.m
//  ELife
//
//  Created by feng lu on 11-5-17.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "IndexPageViewControll.h"
#import "SpecialCustomerController.h"
#import "FilmTicketIndexViewController.h"
#import "FlightSearchController.h"
#import "GameRootController.h"
#include "GDataXMLNode.h"
#import "M13UserDefaults.h"
#import "RegisterController.h"
#import "AlertView.h"
#import "TrainIndexViewController.h"
#import "UserInfoPageController.h"
#import "MobilePhoneChargeIndexViewController.h"
#import "ShoppingMallController.h"
#import "TicketBusinessRootController.h"

@implementation IndexPageViewControll

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [paomaView release];
    [cardContent release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    app = [ELifeAppDelegate App];

    [app controllNum:0 setNavigationBar:YES animated:YES];
    
    [self openMyImage];
    
    [self showMyUser];
    /*
    NSArray* loginInfo = [M13UserDefaults getUserDefaultsArray:USERINFO_NAMEANDPASSWORD];
    UILabel* lable1 = (UILabel*)[self.view viewWithTag:1010];
    UILabel* lable2 = (UILabel*)[self.view viewWithTag:1012];
    
    UIButton* topbutton1 = (UIButton*)[self.view viewWithTag:1011];
    UIButton* topbutton2 = (UIButton*)[self.view viewWithTag:1013];
    if (loginInfo == nil || [loginInfo count] == 0) {
        [lable1 setText:@"您还未登录"];
        [lable2 setText:@"您还未登录"];
        
        [topbutton1 addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton2 addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    }else
    {
        
        [topbutton1 setTitle:@"注销" forState:UIControlStateNormal];
        [topbutton2 setTitle:@"详细" forState:UIControlStateNormal];
        
        [topbutton1 addTarget:self action:@selector(zhuxiaoAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton2 addTarget:self action:@selector(xiangxirAction) forControlEvents:UIControlEventTouchUpInside];
    }
    */
    
    cardNum = 0;
//    NSURL* url = [NSURL URLWithString:@"http://61.160.251.8:1235/momall/init_info.php"];
//    
//    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
//    [[app httpRequestPoint] openUrl:dic target:self];
    
    
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@init_info.php?", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil]]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];

    
    
    
    paomaView = [[PaomaViewControll alloc] initWithFrame:CGRectMake(104, 48, 129, 20)];
    [self.view addSubview:paomaView];
    
    //[paomaView paoma];
    
    
    [self creatCardContent];
    UIButton* button1 = (UIButton*)[self.view viewWithTag:1001];
    [button1 setImage:[UIImage imageNamed:@"1-14.png"] forState:UIControlStateNormal];
    
    UIButton* button2 = (UIButton*)[self.view viewWithTag:1002];
    [button2 setImage:[UIImage imageNamed:@"1-13.png"] forState:UIControlStateNormal];
    
    UIButton* button3 = (UIButton*)[self.view viewWithTag:1003];
    [button3 setImage:[UIImage imageNamed:@"1-16.png"] forState:UIControlStateNormal];
    
    UIButton* button4 = (UIButton*)[self.view viewWithTag:1004];
    [button4 setImage:[UIImage imageNamed:@"1-17.png"] forState:UIControlStateNormal];
    
    NSArray* ico = [NSArray arrayWithObjects:@"1-21.png", @"1-22.png",@"1-23.png",@"1-24.png",@"1-25.png",nil];
    [cardContent setImagePathArray:ico target:self];
    [self.view addSubview:cardContent.view];

}



#pragma 设置头像
-(void) openMyImage
{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    NSLog(@"%@",documentDir);
    
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSString *imageFile = [documentDir stringByAppendingPathComponent:@"temp.jpg"];
    BOOL find = [fileManager fileExistsAtPath:imageFile];
    
    NSLog(@"f=%i", find);
    
    UIButton* buttonimage = (UIButton*)[self.view viewWithTag:1050];
    [buttonimage setImage:[UIImage imageWithContentsOfFile:imageFile] forState:UIControlStateNormal];
}


-(void) showMyUser
{
    NSArray* loginInfo = [M13UserDefaults getUserDefaultsArray:USERINFO_NAMEANDPASSWORD];
    UILabel* lable1 = (UILabel*)[self.view viewWithTag:1010];
    UILabel* lable2 = (UILabel*)[self.view viewWithTag:1012];
    
    UIButton* topbutton1 = (UIButton*)[self.view viewWithTag:1011];
    UIButton* topbutton2 = (UIButton*)[self.view viewWithTag:1013];
    if (loginInfo == nil || [loginInfo count] == 0) {
        [topbutton1 setTitle:@"登录" forState:UIControlStateNormal];
        [topbutton2 setTitle:@"注册" forState:UIControlStateNormal];
        
        [lable1 setText:@"您还未登录"];
        [lable2 setText:@"您还未登录"];
        
        
        [topbutton1 removeTarget:self action:@selector(zhuxiaoAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton2 removeTarget:self action:@selector(xiangxirAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton1 addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton2 addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    }else
    {
        
        [topbutton1 setTitle:@"注销" forState:UIControlStateNormal];
        [topbutton2 setTitle:@"详细" forState:UIControlStateNormal];
        
        [topbutton1 removeTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton2 removeTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton1 addTarget:self action:@selector(zhuxiaoAction) forControlEvents:UIControlEventTouchUpInside];
        [topbutton2 addTarget:self action:@selector(xiangxirAction) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [paomaView paoma];
}

- (void)viewWillAppear:(BOOL)animated
{
    [app controllNum:0 setNavigationBar:YES animated:YES];
}


-(void) creatCardContent
{
    cardContent = [CardContentViewControll alloc];
    [cardContent.view setBackgroundColor:[UIColor clearColor]];
    cardContent.view.frame = CGRectMake(40, 160, 250, 250);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)showSpecialCustomers
{
    SpecialCustomerController *specialCustomersController = [[SpecialCustomerController alloc] initWithNibName:@"SpecialCustomerController" bundle:nil];
    [self.navigationController pushViewController:specialCustomersController animated:YES];
    [specialCustomersController release];
}

-(IBAction)selectButtonAction:(id)sender
{
    [cardContent.view removeFromSuperview];
    [cardContent release];
    [self creatCardContent];
    UIButton* button = (UIButton*)sender;
    if (button.tag == 1002) {
        cardNum = 1;
        NSArray* ico = [NSArray arrayWithObjects:@"1-7.png", @"1-8.png",@"1-9.png",@"1-10.png",nil];
        [cardContent setImagePathArray:ico target:self];
        
        [button setImage:[UIImage imageNamed:@"1-12.png"] forState:UIControlStateNormal];
        
        UIButton* button2 = (UIButton*)[self.view viewWithTag:1001];
        [button2 setImage:[UIImage imageNamed:@"1-15.png"] forState:UIControlStateNormal];
    }else if(button.tag == 1001)
    {
        cardNum = 0;
        NSArray* ico = [NSArray arrayWithObjects:@"1-21.png", @"1-22.png",@"1-23.png",@"1-24.png",@"1-25.png",nil];
        [cardContent setImagePathArray:ico target:self];
        
        [button setImage:[UIImage imageNamed:@"1-14.png"] forState:UIControlStateNormal];
        
        UIButton* button1 = (UIButton*)[self.view viewWithTag:1002];
        [button1 setImage:[UIImage imageNamed:@"1-13.png"] forState:UIControlStateNormal];
    }
    [self.view addSubview:cardContent.view];
}


-(IBAction) selectShoppingMall
{
    ShoppingMallController* shop = [ShoppingMallController alloc];
    [self.navigationController pushViewController:shop animated:YES];
    [shop release];
}


#pragma mark 内容按钮触发
#pragma mark content button action
-(void) contentButtonAction:(id)sender
{
    //根据当前标签类型＋内容按钮tag判断触发哪些事件
    
    // for test
    UIButton* button = (UIButton*)sender;
    NSLog(@"%i", button.tag);
    if (cardNum == 0) {
        switch (button.tag)
        {
            case 0:
            {
                //电影                
                [app controllNum:0 setNavigationBar:NO animated:YES];
                FilmTicketIndexViewController *controller = [[FilmTicketIndexViewController alloc] initWithNibName:@"FilmTicketIndexView" bundle:nil];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];
                break;
            }
            case 1:
            {
                
                //机票
                [app controllNum:0 setNavigationBar:NO animated:YES];
                FlightSearchController *controller = [[FlightSearchController alloc] initWithNibName:@"FlightSearchController" bundle:nil];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];
                break;
            }
            case 2:
            {
                
                //彩票
                break;
            }
            case 3:
            {
                
                //火车票 TrainIndexViewController
                [app controllNum:0 setNavigationBar:NO animated:YES];
                TrainIndexViewController *controller = [[TrainIndexViewController alloc] initWithNibName:@"TrainIndexView" bundle:nil];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];
                break;
            }
            case 4:
            {
                
                //票务
                [app controllNum:0 setNavigationBar:NO animated:YES];
                TicketBusinessRootController *nextController = [[TicketBusinessRootController alloc] initWithNibName:@"TicketBusinessRootController" bundle:nil];
                [self.navigationController pushViewController:nextController animated:YES];
                [nextController release];
                break;
            }
        }
    }else if (cardNum == 1) {
        switch (button.tag)
        {
            case 0:
            {
                //租车
                [app controllNum:0 setNavigationBar:NO animated:YES];
                MobilePhoneChargeIndexViewController *controller = [[MobilePhoneChargeIndexViewController alloc] initWithNibName:@"MobilePhoneChargeIndexView" bundle:nil];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];
                break;
            }
            case 1:
            {
                //点卡
                static NSString *nibName = @"GameRootController";
                GameRootController *controller = [[GameRootController alloc]initWithNibName:nibName bundle:nil];
                [self.navigationController pushViewController:controller animated:YES];
                [controller release];
                break;
            }
            case 2:
            {
                
                //捐赠
                break;
            }
            case 3:
            {
                
                //煤水电
                break;
            }
            
        }

    }
    
    
//    static NSString *loginUrl = @"http://61.160.251.8:1235/momall/cinema.php";
//    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
//    [param setObject:@"get_city_list" forKey:@"action"];
//    
//    
//    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:loginUrl], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
//    
//    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
//    
//    [param release];

    
    /*
//    FlightSearchController *controller = [[FlightSearchController alloc] initWithCustomer];
//    [self.navigationController pushViewController:controller animated:YES];
//    [controller release];
    */
    
    /*
    static NSString *version = @"edsh_iphone_000x000_common_common_11001_V1.00_501";
    static NSString *loginUrl = @"http://61.160.251.8:1235/momall/user.php";
    
    NSString* md5Pass = [NSString md5:@"xiaozhi"];
    NSLog(@"--------md5Pass:--------\n%@", md5Pass);
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
    [param setObject:@"register" forKey:@"action"];
    [param setObject:@"liuqinan" forKey:@"username"];
    [param setObject:@"xiaozhi" forKey:@"password"];
    [param setObject:@"13911500504" forKey:@"phone"];
    [param setObject:version forKey:@"version"];
    
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:loginUrl], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
     */
//    FilmTicketIndexViewController *controller = [[FilmTicketIndexViewController alloc] initWithNibName:@"FilmTicketIndexView" bundle:nil];
//    [self.navigationController pushViewController:controller animated:YES];
//    [controller release];
     
}

#pragma mark -
#pragma mark 联网回调
- (void)iRequestFinished:(NSData *)request
{
    /*
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:request] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    [retStr release];
     */
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:request] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------root element:--------\n%@",rootElement);
    NSArray* children = [rootElement children];
    //NSLog(@"--------root's children:--------\n%@", children);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    //NSLog(@"--------body:--------\n%@", bodyElement);
    //某个具体节点的文本内容
    NSMutableArray* tempmarArray = [NSMutableArray arrayWithCapacity:10];
    NSArray* marquees = [[[bodyElement elementsForName:@"marquees"] objectAtIndex:0] children];
    for (int i = 0; i<[marquees count]; i++) {
        NSString* temp = [[marquees objectAtIndex:i] stringValue];
        NSLog(@"%@", temp);
        [tempmarArray addObject:temp];
        
    }
    [M13UserDefaults setUserDefaults:tempmarArray defaultName:USERINFO_MARQUEES];
    
//    NSLog(@"%@", [[[[[bodyElement elementsForName:@"businessinfo"] objectAtIndex:0]elementsForName:@"promotions"] objectAtIndex:0]elementsForName:@"promotion"]);
    GDataXMLElement* promotion = [[[[[[bodyElement elementsForName:@"businessinfo"] objectAtIndex:0]elementsForName:@"promotions"] objectAtIndex:0]elementsForName:@"promotion"] objectAtIndex:0];
    NSString* promotion_name = [[[promotion elementsForName:@"promotion_name"] objectAtIndex:0] stringValue];
    NSString* promotion_url = [[[promotion elementsForName:@"promotion_url"] objectAtIndex:0] stringValue];
//    NSLog(@"%@", promotion_name);
    [app setTuangou:[NSArray arrayWithObjects:promotion_name, promotion_url, nil]];
    
    NSString* content = [[[bodyElement elementsForName:@"marquees"] objectAtIndex:0] stringValue];
    NSLog(@"--------body's content:--------\n%@", content);
    
    [paomaView.labelShow setText:content];
    
    bodyElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"--------head:--------\n%@", bodyElement);
    //某个具体节点的文本内容
    content = [[[bodyElement elementsForName:@"msgstatus"]objectAtIndex:0] stringValue];
    NSLog(@"--------body's msgstatus:--------\n%@", content);
    
    if (content == nil || [content isEqualToString:@"0"]) {
        [app setInfoValue:@"0" setInfoKey:USERINFO_MSGSTATUS];
    }else if([content isEqualToString:@"1"])
    {
        [app setInfoValue:@"1" setInfoKey:USERINFO_MSGSTATUS];
    }
    [doc release];
    
    NSArray* info = [M13UserDefaults getUserDefaultsArray:USERINFO_NAMEANDPASSWORD];
    if (info != nil && [info count]>0) {
//        NSString *loginUrl = @"http://61.160.251.8:1235/user.php";
        NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@user.php?", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil]]];
        NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:4];
        [param setObject:@"login" forKey:@"action"];
        [param setObject:[info objectAtIndex:0] forKey:@"username"];
        [param setObject:[info objectAtIndex:1] forKey:@"password"];
        [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
        
        
        NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"loginFinish:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
        
        [[app httpRequestPoint]openUrl:dic postParam:param target:self];
        
        [param release];
    }else
    {
        [app finishMyInfoPage];
    }
    
//    NSLog(@"###%@", [GetMyData getMarquees]);
}



-(void) loginFinish:(NSData*) data
{
//    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:data] encoding:NSUTF8StringEncoding];
//    NSLog(@"%@", retStr);
//    [retStr release];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:data] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------root element:--------\n%@",rootElement);
    NSArray* children = [rootElement children];
    //NSLog(@"--------root's children:--------\n%@", children);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    //NSLog(@"--------body:--------\n%@", bodyElement);
    //某个具体节点的文本内容
    NSString* username = [[[bodyElement elementsForName:@"username"]objectAtIndex:0] stringValue];
    NSString* account = [[[bodyElement elementsForName:@"account"]objectAtIndex:0] stringValue];
    score = [[[[bodyElement elementsForName:@"score"]objectAtIndex:0] stringValue] intValue];
    daijinquan = [[[[bodyElement elementsForName:@"daijinquan"]objectAtIndex:0] stringValue] intValue];

    UILabel* lable1 = (UILabel*)[self.view viewWithTag:1010];
    UILabel* lable2 = (UILabel*)[self.view viewWithTag:1012];
    
    [lable1 setText:username];
    [lable2 setText:[NSString stringWithFormat:@"余额：%@", account]];
    
    [doc release];
    
    [app finishMyInfoPage];
}

- (void)iRequestFailed
{
  //  [AlertView showAlert:@"网络链接失败"];
    [app finishMyInfoPage];
}


#pragma mark -
#pragma mark 注册 登录按钮处理 注销 详情
- (void)loginAction
{
    LoginController* lc = [[LoginController alloc] init:self];
    [self.navigationController pushViewController:lc animated:YES];
    [lc release];
    
}

- (void) registerAction
{
    RegisterController* regCon = [[RegisterController alloc] init:self];
    [self.navigationController pushViewController:regCon animated:YES];
    [regCon release];
}

-(void) zhuxiaoAction
{
    [M13UserDefaults setUserDefaults:nil defaultName:USERINFO_NAMEANDPASSWORD];
    [self showMyUser];
}

-(IBAction) xiangxirAction
{
    
    UILabel* lable1 = (UILabel*)[self.view viewWithTag:1010];
    UILabel* lable2 = (UILabel*)[self.view viewWithTag:1012];
    
    UserInfoPageController* userinfo = [[UserInfoPageController alloc] init:self];
    [self.navigationController pushViewController:userinfo animated:YES];
    [userinfo.name setText:lable1.text];
    [userinfo.account setText:lable2.text];
    [userinfo.score setText:@"0.00"];
    [userinfo.daijinquan setText:@"0.00"];
    [userinfo release];
}


#pragma mark -
#pragma mark 登录成功后的付值
-(void) registerOver:(NSString*) username
{
    [self showMyUser];
    UILabel* lable1 = (UILabel*)[self.view viewWithTag:1010];
    UILabel* lable2 = (UILabel*)[self.view viewWithTag:1012];
    
    [lable1 setText:username];
    [lable2 setText:[NSString stringWithFormat:@"余额：%@", @"0.00"]];
}

#pragma mark -
#pragma mark 注销 等等按钮

@end
